<template>
  <div class="u-page u-page-process-bg u-box">
    <!-- 标题 -->
    <div class="u-cl-white u-pt-20 u-pb-20">
      <div class="u-fz-26 u-font-bold">{{ form.partnerName }}的工作成果</div>
      <div class="u-number u-pb-10 u-pt-10">
        请尽快验收第{{ form.subTaskSortNum }}期（{{ form.subTaskSortNum }}/{{
          form.totalPeriods
        }}）的工作成果。
      </div>
    </div>

    <!-- 弹窗【审批意见】 -->
    <u-modal
      ref="uModal"
      title="审批意见"
      z-index="9999"
      v-model="showApprovalModal"
      show-cancel-button
      confirm-text="完成"
      cancel-text="取消"
      @confirm="submitStep2"
    >
      <div class="u-p-20">
        <u-form-item
          label="成果满意度"
          prop="satisfiedDegree"
          label-width="40%;"
        >
          <u-input
            type="number"
            style="float: left; display: inline; width: 90%"
            v-model="form.satisfiedDegree"
            min="1"
            max="100"
            @input="calculateCommission"
          ></u-input>
          <span style="float: right; display: inline; line-height: 70rpx"
            >%</span
          >
        </u-form-item>

        <u-form-item label="最终佣金" prop="ActualPrice" label-width="40%;">
          <u-input
            style="float: left; display: inline; width: 90%"
            disabled="true"
            v-model="form.actualPrice"
          ></u-input>
          <span style="float: right; display: inline; line-height: 70rpx"
            >元</span
          >
        </u-form-item>

        <u-form-item
          label="审批理由"
          prop="ApprovalReasons"
          label-position="top"
        >
          <u-input
            type="textarea"
            maxlength="1000"
            height="150"
            v-model="form.approvalReasons"
            placeholder="请填写审批理由"
          ></u-input>
        </u-form-item>
      </div>
    </u-modal>

    <!-- 弹窗【第1,2次，退回理由】 -->
    <u-modal
      ref="uModal"
      title="填写理由"
      z-index="9999"
      v-model="showRejectModal"
      show-cancel-button
      confirm-text="提交"
      cancel-text="取消"
      @confirm="goToPrevNode"
    >
      <div class="u-p-20">
        <u-input
          type="textarea"
          :placeholder="_placeholder"
          maxlength="500"
          height="150"
          v-model="tmpRemark"
        ></u-input>
      </div>
    </u-modal>

    <!-- 表单 -->
    <div
      class="rule-form rule-form-input-right u-box u-radius-lg u-shadow u-bcl-white"
    >
      <div class="see_template" @click="showTaskDetail">
        点击查看项目实施计划
      </div>
      <u-form ref="uForm" :model="form">
        <u-form-item
          :label="'第' + form.subTaskSortNum + '期'"
          prop="subTaskSortNum"
          label-position="top"
        >
        </u-form-item>

        <u-form-item
          label="工作内容与交付标准"
          label-position="top"
          prop="contentAndRequire"
        >
          <div class="u-text-left">{{ form.contentAndRequire }}</div>
        </u-form-item>

        <u-form-item label="本期佣金(元)" prop="SubTaskPrice">
          <div class="u-text-right">{{ form.subTaskPrice }}</div>
        </u-form-item>

        <u-form-item label="交付日期" prop="deliveryDate">
          <div class="u-text-right">{{ form.deliveryDate }}</div>
          <div class="Tips" v-if="isOvertime">
            <span style="color: #f02323" v-html="TipInfo"></span>
          </div>
        </u-form-item>

        <div>
          <div
            v-for="(formItem, index) in taskResultList"
            :key="index"
            style="margin-top: 10rpx"
          >
            <u-form-item
              :label="'第' + formItem.sort + '次工作成果'"
              label-position="top"
              :border-bottom="false"
            >
              <div class="u-text-left">{{ formItem.result }}</div>
            </u-form-item>

            <u-form-item
              :label="'第' + formItem.sort + '次返修意见'"
              label-position="top"
              v-if="formItem.remark"
            >
              <div class="u-text-left">{{ formItem.remark }}</div>
            </u-form-item>
          </div>
        </div>
      </u-form>

      <!-- 按钮 -->
      <div>
        <div style="margin-top: 40rpx">
          <u-button
            type="primary"
            :disabled="isClick"
            shape="circle"
            @click="submitStep1"
          >
            通过
          </u-button>
        </div>

        <div style="margin-top: 20rpx" v-if="form.returnNum != '2'">
          <u-button
            type="error"
            :disabled="isClick"
            shape="circle"
            @click="reject"
          >
            不通过
          </u-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        deliveryId: "", // 交付id
        workSubject: "", // 项目名称
        returnNum: "", // 返修次数
        subTaskSortNum: "", // 第几期
        contentAndRequire: "-无-", // 工作内容与交付标准
        deliveryDate: "-无-", // 交付日期
        subTaskPrice: "-无-", // 本期佣金
        totalPeriods: "", // 总期数
        initiatorId: "", // 发起人id
        initiatorName: "", // 发起人昵称
        partnerId: "", // 拍档id
        partnerName: "", // 拍档昵称
        satisfiedDegree: null, // 成果满意度
        actualPrice: "", // 最终佣金
        approvalReasons: "", // 审批理由
        orderId: "", // 订单id
        paymentDate: "", // 付款日期
        taskNumber: "", // 单号
      },
      taskResultList: [], // 工作成果和返修意见(包含返修的)
      TipInfo: "",
      today: "",
      showRejectModal: false,
      showApprovalModal: false,
      isClick: false, // 提交按钮是否可点击，默认可点击
      taskNumber: "",
      tmpRemark: "", // 返修意见
      _placeholder: "",
      isOvertime: false, // 是否超时
    };
  },

  onLoad(options) {
    this.taskNumber = options.taskNumber;
    this.form.deliveryId = options.deliveryId;
    const loginRes = this.checkLogin();
    if (!loginRes) {
      return false;
    }
    // 删除数组的第一个空元素
    this.taskResultList.splice(0, 1);
  },

  mounted() {
    this.initFormData();
  },

  methods: {
    /**
     * 初始化表单数据
     */
    async initFormData() {
      // 显示 loading 提示框
      uni.showLoading({
        mask: true,
      });
      this.isClick = true;
      const userInfo = uni.getStorageSync("userInfo");
      const requestData = {
        systemid: "meily",
        url: "/expert/delivery/detail",
        userId: userInfo.userId,
        taskNumber: this.taskNumber,
        deliveryId: this.form.deliveryId,
        loading: false, // 默认发起请求会有一个全局的Loading，设置false可去掉
      };
      let result = await this.$u.api.unifyMiniRest(requestData);
      const { code, data, taskResultList, msg } = JSON.parse(
        JSON.stringify(result)
      );
      if (code == "200") {
        // 业务数据
        const {
          initiatorId,
          initiatorName,
          partnerId,
          partnerName,
          workSubject,
          subTaskSortNum,
          contentAndRequire,
          subTaskPrice,
          totalPeriods,
          deliveryDate,
          returnNum,
        } = data;
        this.form.initiatorId = initiatorId; // 发起人id
        this.form.initiatorName = initiatorName; // 发起人昵称
        this.form.partnerId = partnerId; // 拍档id
        this.form.partnerName = partnerName; // 拍档昵称
        this.form.workSubject = workSubject; // 项目名称
        this.form.subTaskSortNum = subTaskSortNum; // 第几期
        this.form.contentAndRequire = contentAndRequire; // 工作内容与交付标准
        this.form.subTaskPrice = subTaskPrice; // 本期佣金
        this.form.totalPeriods = totalPeriods; // 总期数
        this.form.deliveryDate = deliveryDate; // 交付日期
        this.form.returnNum = returnNum; // 返修次数

        this.form.satisfiedDegree = 100; // 成果满意度
        this.calculateCommission(this.form.satisfiedDegree); // 最终佣金
        // 工作成果、返修意见以及附件(包含返修的)
        if (taskResultList) {
          this.taskResultList = taskResultList;
        }
        // 默认日期初始化为今天
        let nowDate = new Date();
        this.today = this.$u.timeFormat(nowDate, "yyyy-mm-dd"); // 将格式转为 yyyy-MM-dd
        let diff = this.comparisonDate(this.today, this.form.deliveryDate);
        if (diff > 0) {
          this.isOvertime = true;
          this.TipInfo = "当前已超时" + diff + "天";
        }
        uni.hideLoading();
        this.isClick = false;
      } else {
        uni.hideLoading();
        this.$u.toast(msg);
        this.isClick = false;
      }
    },

    /**
     * 根据 成果满意度 计算 最终佣金
     */
    calculateCommission(ratio) {
      if (this.isNotNull(ratio)) {
        ratio = ratio / 100;
      }
      this.form.actualPrice = Number(this.form.subTaskPrice) * ratio;
    },

    /**
     * 提交流程---审批意见
     */
    async submitStep1() {
      this.showApprovalModal = true;
    },

    /**
     * 确认提交流程
     */
    async submitStep2() {
      // 显示 loading 提示框
      uni.showLoading({
        mask: true,
      });
      // 设置按钮为不可点击
      this.isClick = true;
      // 保存 成果满意度、最终佣金、审批理由
      const userInfo = uni.getStorageSync("userInfo");
      let result = await this.$u.api.unifyMiniRest({
        systemid: "meily",
        url: "/expert/delivery/verify/user",
        partnerId: this.form.partnerId,
        partnerName: this.form.partnerName,
        initiatorId: userInfo.userId,
        initiatorName: userInfo.nickName,
        taskNumber: this.taskNumber,
        deliveryId: this.form.deliveryId,
        actualPrice: this.form.actualPrice, // 最终佣金
        satisfiedDegree: this.form.satisfiedDegree, // 成果满意度
        approvalReasons: this.form.approvalReasons, // 审批理由
        loading: false, // 默认发起请求会有一个全局的Loading，设置false可去掉
      });
      if (result.code == "200") {
        uni.hideLoading();
        this.isClick = false;
        uni.reLaunch({
          url:
            "/pages_private_scene1/ExpertCooperate/common/result?mode=43&SubDocUnid=" +
            this.taskNumber +
            "&WorkSubject=" +
            this.form.workSubject +
            "&PartnerName=" +
            this.form.partnerName +
            "&SubTaskSortNum=" +
            this.form.subTaskSortNum +
            "&TotalPeriods=" +
            this.form.totalPeriods,
        });
      } else {
        this.$u.toast(result.msg);
        this.isClick = false;
      }
    },

    /**
     * 退回提醒信息
     */
    reject() {
      // 判断是第几次退回，显示不同的提示语
      if (this.form.returnNum == "0") {
        this._placeholder =
          "请填写不通过验收的理由，提交后该工作者需重新提交成果。（第1次返修）";
        this.showRejectModal = true;
      }
      if (this.form.returnNum == "1") {
        this._placeholder =
          "请填写不通过验收的理由，提交后该工作者需重新提交成果。（第2次返修）";
        this.showRejectModal = true;
      }
    },

    /**
     * 退回到拍档验收节点
     */
    async goToPrevNode() {
      if (this.form.returnNum === "0" || this.form.returnNum === "1") {
        if (!this.tmpRemark) {
          this.$u.toast("不通过的理由不能为空！");
          return;
        }
        try {
          uni.showLoading({ mask: true });
          const userInfo = uni.getStorageSync("userInfo");
          const requestData = {
            systemid: "meily",
            url: "/expert/delivery/reject/user",
            deliveryId: this.form.deliveryId,
            initiatorId: userInfo.userId,
            partnerId: this.form.partnerId,
            taskNumber: this.taskNumber,
            tmpRemark: this.tmpRemark,
            loading: false,
          };
          const result = await this.$u.api.unifyMiniRest(requestData);
          if (result.code === "200") {
            uni.reLaunch({
              url: "/pages_private_scene1/ExpertCooperate/common/result?mode=42",
            });
          }
          uni.hideLoading();
        } catch (error) {
          console.error("流程回退出错：", error);
          uni.hideLoading();
        }
      }
    },

    /**
     * 点击查看项目实施计划（用户写的实施计划）
     */
    async showTaskDetail() {
      await this.$u.route(
        "/pages_private_scene1/ExpertCooperate/partnerWorkPlan?taskNumber=" +
          this.taskNumber +
          "&pubPlan=1&userId=" +
          this.form.partnerId +
          "&subject=" +
          this.form.workSubject
      );
    },

    /**
     * 计算日期差
     * @param {string} startTime - 开始日期（格式：YYYY-MM-DD）
     * @param {string} endTime - 结束日期（格式：YYYY-MM-DD）
     * @returns {number} - 返回天数差（大于0：开始日期 > 结束日期）
     */
    comparisonDate(startTime, endTime) {
      const start_date = new Date(startTime);
      const end_date = new Date(endTime);
      const ms = start_date - end_date;
      return Math.floor(ms / (1000 * 60 * 60 * 24));
    },
  },
};
</script>

<style lang="scss" scoped>
.Tips {
  font-size: 22 rpx;
  line-height: 24 rpx;
  margin-top: 12 rpx;
  color: #9a9a9a;
  padding: 0;
  margin: 0;
  word-break: break-all;
  -webkit-overflow-scrolling: touch;
  -webkit-tap-highlight-color: transparent;
  text-size-adjust: 100%;
  text-align: right !important;
  box-sizing: border-box;
}

.see_template {
  text-align: center;
  color: red;
  text-decoration: underline;
  padding-top: 20 rpx;
}
</style>
